package com.zzyl.config;

import com.zzyl.properties.MinioConfigProperties;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.net.URL;

@Slf4j
@ConditionalOnBean(MinioAutoConfig.class)
@Component
public class MinioFileStorageService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfigProperties minioConfigProperties;

    /**
     * 上传文件
     * @param objectName  文件名
     * @param inputStream  文件流对象
     * @return 文件访问URL
     */
    public String store(String objectName, InputStream inputStream) {
        if (inputStream == null) {
            log.error("上传文件：objectName{}文件流为空", objectName);
            return null;
        }

        log.info("Minio文件上传开始：{}", objectName);

        try {
            // 创建上传请求
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioConfigProperties.getBucketName())
                    .object(objectName)
                    .stream(inputStream, inputStream.available(), -1)
                    .build();

            // 执行上传
            ObjectWriteResponse response = minioClient.putObject(putObjectArgs);
            log.info("Minio文件上传成功：{}", response.object());

            // 使用Minio的直接URL格式
            return String.format("http://%s/%s/%s",
                    minioConfigProperties.getEndpoint(),
                    minioConfigProperties.getBucketName(),
                    objectName);

        } catch (Exception e) {
            log.error("Minio文件上传失败：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 根据url删除文件
     * @param pathUrl  完整的文件访问URL
     */
    public void delete(String pathUrl) {
        if (!StringUtils.hasText(pathUrl)) {
            return;
        }

        try {
            // 解析URL获取对象名
            String objectName = parseObjectNameFromUrl(pathUrl);
            if (objectName == null) {
                return;
            }

            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                    .bucket(minioConfigProperties.getBucketName())
                    .object(objectName)
                    .build();

            minioClient.removeObject(removeObjectArgs);
            log.info("Minio文件删除成功：{}", objectName);
        } catch (Exception e) {
            log.error("Minio文件删除失败：{}", e.getMessage());
        }
    }

    /**
     * 从Minio URL中解析出对象名
     * @param fileUrl 文件URL
     * @return 对象名
     */
    private String parseObjectNameFromUrl(String fileUrl) {
        try {
            // 从URL格式 http://endpoint/bucket/object 中提取对象名
            URL url = new URL(fileUrl);
            String path = url.getPath();

            // 移除开头的斜杠和桶名部分
            if (path.startsWith("/" + minioConfigProperties.getBucketName() + "/")) {
                return path.substring(minioConfigProperties.getBucketName().length() + 2);
            }

            // 备选方案：获取最后一个斜杠后的内容
            int lastSlashIndex = path.lastIndexOf('/');
            if (lastSlashIndex > 0) {
                return path.substring(lastSlashIndex + 1);
            }

            log.warn("无法从URL中解析对象名: {}", fileUrl);
            return null;
        } catch (Exception e) {
            log.error("解析Minio URL时出错: {}", e.getMessage());
            return null;
        }
    }
}